import json

def lisp_to_jsonlang(expr):
    """将 Lisp S-表达式转换为 JSONLang"""
    if isinstance(expr, (int, float, str, bool)) or expr is None:
        return expr  # 原子值直接返回
    elif isinstance(expr, list):
        if not expr:
            return {"list": []}
        head = expr[0]
        if head == 'let':
            # 处理 (let ((var val) ...) body)
            bindings = [{"var": var, "value": lisp_to_jsonlang(val)} 
                       for var, val in expr[1]]
            return {"let": bindings, "body": lisp_to_jsonlang(expr[2])}
        elif head == 'lambda':
            # 处理 (lambda (params) body)
            return {"lambda": {"params": expr[1], "body": lisp_to_jsonlang(expr[2])}}
        elif head == 'if':
            # 处理 (if cond then else)
            return {"if": {
                "condition": lisp_to_jsonlang(expr[1]),
                "then": lisp_to_jsonlang(expr[2]),
                "else": lisp_to_jsonlang(expr[3])
            }}
        elif head == 'define':
            # 处理 (define (name params) body)
            return {"define": {
                "name": expr[1][0],
                "params": expr[1][1:],
                "body": lisp_to_jsonlang(expr[2])
            }}
        elif head == 'quote':
            # 处理 (quote x)
            return {"quote": lisp_to_jsonlang(expr[1])}
        else:
            # 普通函数调用 (func arg1 arg2)
            return {head: [lisp_to_jsonlang(arg) for arg in expr[1:]]}
    else:
        raise ValueError(f"Unknown expression: {expr}")

# 示例：转换 Lisp 到 JSONLang
lisp_code = ['define', ['factorial', 'n'],
             ['if', ['<=', 'n', 1],
              1,
              ['*', 'n', ['factorial', ['-', 'n', 1]]]]]
jsonlang = lisp_to_jsonlang(lisp_code)
print(json.dumps(jsonlang, indent=2))
